from django.views import View as _
import json
import re
import io
from django.http import HttpResponse, HttpRequest
from django.utils.encoding import smart_str
class View(_):
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.files = None
    @property
    def data(self):
        # print(self.request.content_type)
        request = self.request
        if request.content_type in'application/json':
            return json.loads(request.body)
        elif request.content_type == 'multipart/form-data':
            data,files = self.multipart_form_data()
            '''
            files = {"key":(文件名,文件内容)}
            data = {key1:name1,key2:name2}
            '''
            self.files = files
            return data
        elif request.content_type == 'application/x-www-form-urlencoded':
            body_list = request.body.decode('utf-8').split('&')
            dic = {}
            for key_value in body_list:
                key,value = key_value.split('=')
                if key in dic:
                    if isinstance(dic[key],list):
                        dic[key].append(value)
                    else:
                        dic[key] = [dic[key],value]
                else:
                    dic[key] = value
            return dic
        elif request.content_type == 'text/plain':
            data = {}
            for key in request.GET:
                data[key] = request.GET.getlist(key)
                if len(data[key]) == 1:
                    data[key] = None if data[key][0]=='' else data[key][0]
            return data
        else:
            raise Exception(f'不允许的content-type:{request.content_type}')

    def multipart_form_data(self):
        content_type = self.request.META.get('CONTENT_TYPE', '')
        body = self.request.body

        # 提取 boundary
        boundary = content_type.split("boundary=")[-1].strip()

        # 分隔请求体
        parts = body.split(b'--' + boundary.encode())

        # 去掉前后的空部分
        parts = [p for p in parts if p and p != b'--']

        data = {}
        files = {}

        for part in parts:
            # 检查是否包含分隔符
            if b'\r\n\r\n' not in part:
                continue

            # 尝试分割头部和内容
            try:
                headers, content = part.split(b'\r\n\r\n', 1)
            except ValueError:
                continue  # 跳过格式错误的部分

            content = content.rstrip(b'\r\n')

            # 解析头部
            headers = headers.decode('utf-8')
            header_lines = headers.split('\r\n')
            content_disposition = [line for line in header_lines if line.startswith('Content-Disposition:')][0]
            filename_match = re.search(r'filename="([^"]*)"', content_disposition)
            field_name_match = re.search(r'name="([^"]*)"', content_disposition)

            if filename_match:
                filename = filename_match.group(1)
                field_name = field_name_match.group(1)
                files[field_name] = (filename, content)
            else:
                field_name = field_name_match.group(1)
                data[field_name] = content.decode('utf-8')
        print(data,type(files))
        return data, files